#include "mcbeealgorithm.h"
#include "samegame.h"
#include "beesolver.h"
#include <QDebug>
#include <iostream>
MCbeeAlgorithm::MCbeeAlgorithm()
{
}
SGSolution MCbeeAlgorithm::solve(sameGame samegame)
{
steps.clear();
 return private_solve(samegame);
}

SGSolution MCbeeAlgorithm::private_solve(sameGame samegame,SGSolution bestSolution)
{
    qDebug()<< "###~~KELEJNA ITERACJA~~###";
    std::cout << "###~~KELEJNA ITERACJA~~###" <<std::endl;
    std::vector<SGPoint> groups = samegame.getGroups();
    std::vector<sameGame*> copies(groups.size());
     for(int i=0;i<groups.size();++i)
     {
         copies[i] = new sameGame(samegame);
     }
    int bestPos=-1;
    if(groups.size()==0)
    {

        SGSolution solution;
        solution.BlocksLefted = samegame.getResult();
        solution.score = samegame.getScore();
        solution.steps = steps;
        return solution;
    }
    for(int i=0;i<groups.size();++i)
    {
        qDebug() <<  "###" <<i << " z " << groups.size();
        std::cout << "###" <<i << " z " << groups.size() <<std::endl;
        SolverBeeAlgorithm solver;
        copies[i]->click(groups[i].x,groups[i].y);
        SGSolution solution = solver.solve(*copies[i]);
        if(bestSolution.score<solution.score)
        {
            bestSolution = solution;
            bestPos = i;
        }
    }
    if(bestPos<0)
    {
    steps.push_back(bestSolution.steps[0]);
    sameGame nextnode(samegame);
    nextnode.click(bestSolution.steps[0].x,bestSolution.steps[0].y);
    bestSolution.steps.erase(bestSolution.steps.begin());
    for(int i=0;i<copies.size();++i)
    {
        delete copies[i];
    }
    return private_solve(nextnode,bestSolution);
    }
    else
    {
        steps.push_back(groups[bestPos]);
        sameGame nextnode(*copies[bestPos]);
        for(int i=0;i<copies.size();++i)
        {
            delete copies[i];
        }
       return private_solve(nextnode,bestSolution);
    }
}
